<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <!-- 商户ID选择 - 根据角色显示不同UI -->
      <uni-forms-item name="tenant_id" label="所属商户" required>
        <!-- 管理员可以选择商户 -->
        <uni-data-select 
          v-if="isAdmin" 
          v-model="formData.tenant_id" 
          :localdata="tenantOptions" 
          placeholder="请选择商户">
        </uni-data-select>
        <!-- 商户用户显示只读文本 -->
        <uni-easyinput 
          v-else 
          v-model="formData.tenant_id" 
          disabled>
        </uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="name" label="分类名称" required>
        <uni-easyinput placeholder="分类名称" v-model="formData.name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="sort" label="排序值">
        <uni-easyinput placeholder="排序值（越小越靠前）" type="number" v-model="formData.sort"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="status" label="状态">
        <uni-data-checkbox v-model="formData.status" :localdata="formOptions.status_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="created_at" label="创建时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.created_at"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="updated_at" label="更新时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.updated_at"></uni-datetime-picker>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/food_categories.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'food_categories';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "tenant_id": "",
        "name": "",
        "sort": 100,
        "status": 1,
        "created_at": null,
        "updated_at": null
      }
      return {
        formData,
        formOptions: {
          "status_localdata": [
            {
              "text": "禁用",
              "value": 0
            },
            {
              "text": "启用",
              "value": 1
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        },
        // 新增权限相关属性
        isAdmin: false,        // 是否管理员
        currentTenantId: '',   // 当前商户ID
        tenantOptions: [],     // 商户选项列表
        originData: null       // 原始数据，用于权限检查
      }
    },
    onLoad(e) {
      // 从Storage获取用户信息，而不是Vuex
      const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {}
      this.isAdmin = userInfo.isAdmin === true
      this.currentTenantId = userInfo.tenant_id || ''
      
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      // 加载商户数据
      async loadTenants() {
        try {
          const { result } = await uniCloud.callFunction({
            name: 'get-tenants',
            data: {}
          })
          
          if (result?.data) {
            // 将商户数据转为选择器需要的格式
            this.tenantOptions = result.data.map(tenant => ({
              value: tenant.tenant_id,
              text: tenant.tenant_name || tenant.name || `商户(${tenant.tenant_id})`
            }))
            
            // 添加平台选项
            this.tenantOptions.unshift({
              value: '',
              text: '平台分类'
            })
          }
        } catch (e) {
          console.error('加载商户数据失败', e)
        }
      },
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 最后更新时间
        value.updated_at = Date.now()
        
        // 非管理员不允许修改商户ID
        if (!this.isAdmin) {
          value.tenant_id = this.currentTenantId
        }
        
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("tenant_id,name,sort,status,created_at,updated_at").get().then((res) => {
          const data = res.result.data[0]
          this.originData = {...data} // 保存原始数据
          
          // 权限检查: 非管理员不能编辑其他商户的分类
          if (!this.isAdmin && data.tenant_id !== this.currentTenantId && data.tenant_id !== '') {
            uni.showModal({
              content: '您没有权限编辑此分类',
              showCancel: false,
              success: () => {
                uni.navigateBack()
              }
            })
            return
          }
          
          if (data) {
            this.formData = data
            
            // 加载商户数据(仅管理员)
            if (this.isAdmin) {
              this.loadTenants()
            }
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
